package com.yunbiao.ybbusstopplate.refactoring.ui.dalian;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ArrayUtils;
import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FragmentUtils;
import com.blankj.utilcode.util.UiMessageUtils;
import com.bumptech.glide.Glide;
import com.example.library_hy_advert.system.Cache;
import com.google.gson.internal.LinkedTreeMap;
import com.yunbiao.ybbusstopplate.R;
import com.yunbiao.ybbusstopplate.base.BaseFragment;
import com.yunbiao.ybbusstopplate.base.BaseSettingFragment;
import com.yunbiao.ybbusstopplate.databinding.FragmentDalianNodeSiteBinding;
import com.yunbiao.ybbusstopplate.refactoring.Config;
import com.yunbiao.ybbusstopplate.refactoring.serial.SerialPortServices;
import com.yunbiao.ybbusstopplate.refactoring.ui.adapter.DownSiteAdapter;
import com.yunbiao.ybbusstopplate.refactoring.ui.adapter.UpSiteAdapter;
import com.yunbiao.ybbusstopplate.refactoring.ui.fengxian.RefactoringLogFragment;
import com.yunbiao.ybbusstopplate.refactoring.utils.L;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

public class DalianNodeSiteFragment extends BaseFragment{

    private FragmentDalianNodeSiteBinding binding;

    @Override
    public int getViewId() {
        return R.layout.fragment_dalian_node_site;
    }

    @Override
    protected void initView(){
        binding = DataBindingUtil.bind(requireView());

        UiMessageUtils.getInstance().addListener(ZHIDAParser.Event.UPDATE_INFO.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().addListener(ZHIDAParser.Event.UPDATE_SITE_LIST.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().addListener(ZHIDAParser.Event.BROAD_SITE.getType(),uiMessageCallback);

        binding.rlvList.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false){
            @Override
            public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
                RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(recyclerView.getContext()){
                    @Override
                    public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
                        return (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2);
                    }
                };
                smoothScroller.setTargetPosition(position);
                startSmoothScroll(smoothScroller);
            }
        });

        binding.vSetting.setOnClickListener(v -> {
            FragmentUtils.add(getChildFragmentManager(),new DalianSettingFragment(),binding.flSetting.getId());
        });

        binding.vLog.setOnClickListener(v -> {
            FragmentUtils.add(getChildFragmentManager(),new RefactoringLogFragment(),binding.flSetting.getId());
        });

        String phoneNumber = Cache.getString(Config.Key.PHONE_NUMBER.name(), Config.Default.PHONE_NUMBER);
        if(TextUtils.isEmpty(phoneNumber)){
            binding.tvPhoneNumber.setVisibility(View.GONE);
        } else {
            binding.tvPhoneNumber.setVisibility(View.VISIBLE);
            binding.tvPhoneNumber.setText(String.format("客服热线: %1$s",phoneNumber));
        }

//        testMap();
    }

//    private void testMap(){
//        LinkedHashMap<Integer, ZHIDAParser.Site> upMap = new LinkedHashMap<>();
//        upMap.put(1,new ZHIDAParser.Site(1,"站点1",""));
//        upMap.put(2,new ZHIDAParser.Site(2,"站点2",""));
////        upMap.put(3,new ZHIDAParser.Site(3,"站点3",""));
////        upMap.put(4,new ZHIDAParser.Site(4,"站点4",""));
////        upMap.put(5,new ZHIDAParser.Site(5,"站点5",""));
//        upMap.put(6,new ZHIDAParser.Site(6,"站点6",""));
//        upMap.put(7,new ZHIDAParser.Site(7,"站点7",""));
//        upMap.put(8,new ZHIDAParser.Site(8,"站点8",""));
//        upMap.put(9,new ZHIDAParser.Site(9,"站点9",""));
//
//        LinkedHashMap<Integer, ZHIDAParser.Site> downMap = new LinkedHashMap<>();
//        downMap.put(9,new ZHIDAParser.Site(9,"站点9",""));
////        downMap.put(8,new ZHIDAParser.Site(8,"站点8",""));
//        downMap.put(7,new ZHIDAParser.Site(7,"站点7",""));
//        downMap.put(6,new ZHIDAParser.Site(6,"站点6",""));
//        downMap.put(5,new ZHIDAParser.Site(5,"站点5",""));
//        downMap.put(4,new ZHIDAParser.Site(4,"站点4",""));
//        downMap.put(3,new ZHIDAParser.Site(3,"站点3",""));
////        downMap.put(2,new ZHIDAParser.Site(2,"站点2",""));
//        downMap.put(1,new ZHIDAParser.Site(1,"站点1",""));
//
//        Object[] objects = ZHIDAParser.convertToMixSiteList(upMap, downMap);
//    }

    @Override
    public void initData() {
        SerialPortServices.start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        SerialPortServices.stop();
        EventBus.getDefault().unregister(this);
        UiMessageUtils.getInstance().removeListener(ZHIDAParser.Event.UPDATE_INFO.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().removeListener(ZHIDAParser.Event.UPDATE_SITE_LIST.getType(),uiMessageCallback);
        UiMessageUtils.getInstance().removeListener(ZHIDAParser.Event.BROAD_SITE.getType(),uiMessageCallback);
    }

    private static final String TAG = "NodeSiteFragment";
    private final UiMessageUtils.UiMessageCallback uiMessageCallback = uiMessage -> {
        int id = uiMessage.getId();
        Object object = uiMessage.getObject();
        if(id == ZHIDAParser.Event.UPDATE_SITE_LIST.getType()){
            setSiteList(object);
        } else if(id == ZHIDAParser.Event.BROAD_SITE.getType()){
            broadSite(object);
        } else if(id == ZHIDAParser.Event.UPDATE_INFO.getType()){
            setLineInfo(object);
        }
    };

    private final AtomicBoolean isLoopLine = new AtomicBoolean(false);
    //设置站点列表
    private void setSiteList(Object object){
        Object[] objects = (Object[]) object;
        LinkedList<DalianSiteAdapter.MixSite> mixSiteList = (LinkedList<DalianSiteAdapter.MixSite>) objects[0];
        isLoopLine.set((boolean) objects[1]);

        int spanCount = Math.max(1,mixSiteList.size());
        DalianSiteAdapter siteAdapter = (DalianSiteAdapter) binding.rlvList.getAdapter();
        if(siteAdapter != null){
            binding.rlvList.setAdapter(null);
        }
        binding.rlvList.setLayoutManager(new GridLayoutManager(getContext(), spanCount));
        siteAdapter = new DalianSiteAdapter(mixSiteList);
        binding.rlvList.setAdapter(siteAdapter);
    }

    //设置报站
    private void broadSite(Object object){
        Object[] objects = (Object[]) object;
        if(objects != null){
            int index = (int) objects[1];
            String inOut = (String) objects[2];
            String upDown = (String) objects[3];
            L.d(TAG,"报站：（站序：" + inOut + "，" + ("01".equals(inOut) ? "进站" : "出站") + "，" + ("01".equals(upDown) ? "上行" : "下行"));

            if(isLoopLine.get()){
                upDown = "01";
            }

            DalianSiteAdapter siteAdapter = (DalianSiteAdapter) binding.rlvList.getAdapter();
            if(siteAdapter != null){
                siteAdapter.broadSite(index,inOut,upDown);
            }

            if(isLoopLine.get()){
                binding.ivDirection.setImageResource(R.mipmap.icon_arrow_right);
            } else if ("01".equals(upDown)) {
                binding.ivDirection.setImageResource(R.mipmap.icon_arrow_right);
            } else {
                binding.ivDirection.setImageResource(R.mipmap.icon_arrow_left);
            }
        }
    }

    //设置线路信息
    private void setLineInfo(Object object) {
        String[] strings = (String[]) object;
        String lineName = strings[0];
        String upStartSiteName = strings[1];
        String upRunTime = strings[2];
        String specialUpRunTime = strings[3];
        String downStartSiteName = strings[4];
        String downRunTime = strings[5];
        String specialDownRunTime = strings[6];
        String basePrice = strings[7];
        String upDown = strings[8];

        L.d(TAG,"显示线路信息：（" + Arrays.toString(strings) + "）");

        binding.tvLineName.setText(String.format("%1$s%2$s", lineName, lineName.endsWith("路") ? "" : "路"));

        binding.tvUpStartSite.setText(upStartSiteName);
        binding.tvDownStartSite.setText(downStartSiteName);

//        if("01".equals(upDown)){
//            String upStartTime = "",upEndTime = "";
//            if(!TextUtils.isEmpty(upRunTime)){
//                String[] split = upRunTime.split("-");
//                if(split.length >= 2){
//                    upStartTime = String.format("始车：%s", split[0]);
//                    upEndTime = String.format("末车：%s", split[1]);
//                }
//            }
//            binding.tvUpStartEndTime.setText(upStartTime);
//            binding.tvDownStartEndTime.setText(upEndTime);
//        } else {
//            String downStartTime = "",downEndTime = "";
//            if(!TextUtils.isEmpty(downRunTime)){
//                String[] split1 = downRunTime.split("-");
//                if(split1.length >= 2){
//                    downStartTime = String.format("始车：%s", split1[0]);
//                    downEndTime = String.format("末车：%s", split1[1]);
//                }
//            }
//            binding.tvUpStartEndTime.setText(downStartTime);
//            binding.tvDownStartEndTime.setText(downEndTime);
//        }
//        binding.tvUpSpecialStartEndTime.setText(specialUpRunTime);
//        binding.tvDownSpecialStartEndTime.setText(specialDownRunTime);

//        binding.tvUpStartSite.setText("");
//        binding.tvDownStartSite.setText("");
//        binding.tvUpStartEndTime.setText("");
//        binding.tvDownStartEndTime.setText("");
//        binding.tvUpSpecialStartEndTime.setText("");
//        binding.tvDownSpecialStartEndTime.setText("");

        String upStartTime = "",upEndTime = "";
        if(!TextUtils.isEmpty(upRunTime)){
            String[] split = upRunTime.split("-");
            if(split.length >= 2){
                upStartTime = split[0];
                upEndTime = split[1];
            } else if(split.length == 1){
                upStartTime = split[0];
            } else {
                upStartTime = "";
                upEndTime = "";
            }
        }
        binding.tvUpStartEndTime.setText(String.format("始车：%s   末车：%s", upStartTime, upEndTime));
        binding.tvUpSpecialStartEndTime.setText(specialUpRunTime);

        String downStartTime = "",downEndTime = "";
        if(!TextUtils.isEmpty(downRunTime)){
            String[] split = downRunTime.split("-");
            if(split.length >= 2){
                downStartTime = split[0];
                downEndTime = split[1];
            } else if(split.length == 1){
                downStartTime = split[0];
                downEndTime = "";
            } else {
                downStartTime = "";
                downEndTime = "";
            }
        }
        binding.tvDownStartEndTime.setText(String.format("始车：%s   末车：%s", downStartTime, downEndTime));
        binding.tvDownSpecialStartEndTime.setText(specialDownRunTime);

        binding.tvPrice.setText(String.format("票价：%s元", basePrice));

        binding.tvStartSite.setText(upStartSiteName);
        binding.tvEndSite.setText(downStartSiteName);
        if ("01".equals(upDown)) {
            binding.ivDirection.setImageResource(R.mipmap.icon_arrow_right);
        } else {
            binding.ivDirection.setImageResource(R.mipmap.icon_arrow_left);
        }
    }

    @Override
    public boolean onBackClick() {
        List<Fragment> fragments = FragmentUtils.getFragments(getChildFragmentManager());
        for (int i = fragments.size() - 1; i >= 0; i--) {
            Fragment fragment = fragments.get(i);
            if(fragment instanceof BaseSettingFragment){
                FragmentUtils.remove(fragment);
                return true;
            }
        }
        return false;
    }
}
